<script setup lang="ts">
import {ref, computed, onMounted, watch} from 'vue'
import {useRoute} from 'vue-router'
import {fetchSearch} from "../request/req.ts";
import {useCartStore} from "../stores/cart.ts";
import {ElNotification} from "element-plus";
import router from "../router";
import Image from "../assets/iamge.svg"
import {formatPrice} from "../util/formatPrice.ts";
import {useLogoTextStore} from "../stores/logoText.ts";

const useStore = useLogoTextStore()
interface SearchItem {
  id: number
  title: string
  image: string
  price: number
  rating: number
  reviews: number
  tag?: '新品' | '热卖' | '精选'
}

const cart = useCartStore()

//获取搜索结果
const fetchSearchResult = async () => {
  const res = await fetchSearch({t: route.query.type, k: route.query.keyword})
  allResults.value = res.GoodsList.map((item: any) => ({
    id: item.Id,
    title: item.GoodsName,
    price: item.Pirce,
    rating: item.StarCount / 2,
    image: useStore.getItemById(3)?.text + '/images/UpLoadPic/' + item.PicUrls,
    reviews: item.Views
  }))
}

const route = useRoute()
const keyword = ref('')

// 从路由获取关键词
const getKeywordFromRoute = () => {
  const routeKeyword = route.query.keyword as string
  if (routeKeyword) {
    keyword.value = routeKeyword
  }
}

onMounted(() => {
  getKeywordFromRoute()
  fetchSearchResult()
})

//
const allResults = ref<SearchItem[]>([
  {
    id: 0,
    title: '',
    price: 0,
    rating: 0,
    reviews: 0,
    image: Image
  }
])

const total = computed(() => allResults.value.length)

//添加购物车
const addToCart = (item: SearchItem) => {
  cart.add({
    id: item.id,
    title: item.title,
    image: item.image,
    price: item.price,
    qty: 1,
  })
  ElNotification({
    title: `商品:${item.title}添加成功`,
    type: 'success',
    showClose: false,
    position: 'bottom-right'
  })
}


const goDetail = (id: any) => {
  router.push(`/detail/${id}`)
}
watch(() => route.query.keyword, async (newKeyword) => {
  if (newKeyword) {
    keyword.value = newKeyword as string
  }
  await fetchSearchResult()
})
</script>

<template>
  <div class="search-page">
    <div style="display: flex; justify-content: center; align-items: center" class="title" v-if="keyword">
      <h3 style="font-size: 30px;margin-right: 10px">搜索内容: </h3>
      <p style="font-size: 20px"> {{ keyword }}</p>
    </div>

    <div v-if="total > 0" class="search-grid">
      <div class="card" v-for="item in allResults" :key="item.id">
        <div class="image-wrap" @click="goDetail(item.id)">
          <img :src="item.image" :alt="item.title"/>
          <el-tag v-if="item.tag" class="tag" size="small" type="danger">{{ item.tag }}</el-tag>
        </div>
        <div class="content">
          <el-tooltip placement="top" :content="item.title">
            <div class="name">{{ item.title }}</div>
          </el-tooltip>
          <div class="rate-wrap">
            <el-rate v-model="item.rating" disabled
                     show-score
                     text-color="#ff9900"
                     score-template="{value}"/>
            <span class="reviews">({{ item.reviews }})</span>
          </div>
          <div class="bottom-row">
            <div class="price">HK$ {{ formatPrice(item.price ) }}</div>
            <el-button size="small" type="primary" @click="addToCart(item)">加入購物車</el-button>
          </div>
        </div>
      </div>
    </div>

    <el-empty v-else description="暂无相关结果"/>

  </div>
</template>

<style scoped>
.search-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  margin: 16px 0 24px;
}

.title {
  display: flex;
  align-items: center;
  font-weight: 800;
  color: rgba(212, 212, 212, 0.9);
  margin: 0;
}

.subtitle {
  color: #888;
  margin-top: 6px;
}

.search-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.card {
  background-color: #2c3e50;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform .25s ease, box-shadow .25s ease;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, .12);
}

.image-wrap {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.image-wrap img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.tag {
  position: absolute;
  top: 10px;
  left: 10px;
}

.content {
  padding: 14px;
}

.name {
  font-weight: 700;
  color: #d1d1d1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.rate-wrap {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0 10px;
}

.reviews {
  color: #777;
  font-size: 12px;
}

.bottom-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.price {
  color: #d1d1d1;
  font-weight: 800;
  font-size: 18px;
}

@media (max-width: 768px) {
  .search-page {
    padding: 16px;
  }

  .image-wrap {
    height: 140px;
  }
}
</style>
